﻿using ClosedXML.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using DongFangGuoKai.WMSPlatform.Commn.ExtendModule;
using DongFangGuoKai.WMSPlatform.Domain.Enum;
using DongFangGuoKai.WMSPlatform.Service.BasicApp.Pallet;
using DongFangGuoKai.WMSPlatform.Service.BasicApp.Pallet.DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Collections;
using System.Data;
using System.Security.Claims;
using System.Text;

namespace DongFangGuoKai.WMSPlatform.WebApi.Controllers.BasicData
{
    /// <summary>
    /// 托盘管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class PalletController : BaseController
    {
        private readonly IPalletService palletService;
        private readonly ILogger<PalletController> palletLogger;

        public PalletController(IPalletService palletService,ILogger<PalletController> palletLogger)
        {
            this.palletService = palletService;
            this.palletLogger = palletLogger;
        }


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult AddPallet(PalletDto dto)
        {
            if (string.IsNullOrEmpty(dto.PalletBarcode))
            {
                return Failed( "编码不能为空！",400);
            }
            bool isko = palletService.AddPallet(dto);
            if (isko)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                palletLogger.LogInformation("添加托盘成功，参数为" + dto.ToJson() );
                return Success("添加成功");
            }
            palletLogger.LogError("添加托盘失败，参数为" + dto.ToJson());
            return Failed("添加失败");
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult UpdatePallet(PalletDto dto)
        {
            if (dto.Id <= 0)
            {
                return Failed("Id有误！",400);
            }
            if (string.IsNullOrEmpty(dto.PalletBarcode))
            {
                return Failed( "编码不能为空！",400);
            }
            bool isko = palletService.UpdatePallet(dto);
            if (isko)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int uid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();
                palletLogger.LogInformation("修改托盘成功，参数为" + dto.ToJson());
                return Success("修改成功");
            }
            palletLogger.LogError("修改托盘失败，参数为" + dto.ToJson());
            return Failed("修改失败");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete]
        public IActionResult DelPallet(int ids)
        {
            if (ids <= 0)
            {
                return Failed("Id有误！", 400);
            }
            bool isko = palletService.DelPallet(ids);
            if (isko)
            {
                string uname = HttpContext.User.FindFirstValue("UserName");
                string runame = HttpContext.User.FindFirstValue("RealName");
                int rid = Convert.ToInt32(HttpContext.User.FindFirstValue("Id"));
                string? ip = HttpContext.Connection.RemoteIpAddress?.ToString();

                palletLogger.LogInformation("删除托盘成功，参数为" + ids);
                return Success("删除成功");
            }
            palletLogger.LogError("删除托盘失败，参数为" + ids);
            return Failed("删除失败");
        }

        /// <summary>
        /// 托盘分页查询
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPallets(string? name, int type = -1, int pageIndex = 1, int pageSize = 5)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Failed("分页条件有误！", 400);
            }

            var list = palletService.GetPallets(name, type, pageIndex, pageSize, out int totalCount);
            if (list != null)
            {
                return Success(list, totalCount, "查询成功！");
            }
            return Failed( "查询失败！");
        }

        /// <summary>
        /// 条件查询
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetPallet(int ids)
        {
            if (ids <= 0)
            {
                return Failed( "Id有误！",400);
            }
            var list = palletService.GetPallet(ids);
            return Success(list, "查询成功");
        }

        /// <summary>
        /// 批量添加托盘
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult BatchPalletForm(BatchPalletDTO m)
        {
            if (m.Num <= 0)
            {
                return Failed("参数有误！",400);
            }
            bool result = palletService.AddPalletList(m,out string errMsg);
            if (result)
            {
                palletLogger.LogInformation("批量添加托盘成功，参数为" + m.ToJson());
                return Success( "添加成功");
            }
            palletLogger.LogError("批量添加托盘失败，参数为" + m.ToJson() + ",错误消息：" + errMsg);
            return Failed(errMsg);
        }

        /// <summary>
        /// 托盘打印
        /// </summary>
        /// <param name="codes"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PallPrintCount(string[] codes)
        {
            var IsOk = palletService.PallPrintCount(codes, out string errMsg);
            if (IsOk)
            {
                return Success(errMsg);
            }
            return Failed(errMsg);
        }

        /// <summary>
        /// 生成Excel表格数据
        /// </summary>
        /// <param name="name"></param>
        /// <param name="type"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult PalletExcelData(string? name, int type = -1, int pageIndex = 1, int pageSize = 5)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Failed("分页条件有误！", 400);
            }

            var list = palletService.GetPallets(name, type, pageIndex, pageSize, out int totalCount);
            if (list == null)
            {
                return Failed("查询失败！");
            }
            DataTable dt = new DataTable();
            dt.Columns.Add("托盘名称");
            dt.Columns.Add("托盘编码");
            dt.Columns.Add("字节值");
            foreach (var item in list)
            {
                var byteArray = Encoding.UTF8.GetBytes(item.PalletBarcode);
                string hexString = BitConverter.ToString(byteArray).Replace("-", "");
                dt.Rows.Add(item.PalletName, item.PalletBarcode, hexString);
            }
            using (var workbook = new XLWorkbook())
            {
                // 将DataTable添加到工作表中
                var worksheet = workbook.Worksheets.Add( "Sheet1");
                worksheet.Cell(1, 1).InsertTable(dt);

                // 保存到指定路径
                workbook.SaveAs("SampleData.xlsx");
            }

            return Success(list, totalCount, "查询成功！");
        }
    }
}
